<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RechargePackage;
use App\Models\Order;
use App\Models\User;
use App\Models\UserNumHistory;
use Illuminate\Support\Facades\Http;
use App\Models\UserPromoteRecord;

class MobileRechargeController extends Controller
{
    public function index(RechargePackage $recharge_package)
    {
        //获取运营商，并按权重排序
        $operators = \DB::table('operator')->orderBy('order', 'asc')->get();

        //获取历史充值记录
        $user_num_histories = UserNumHistory::where('user_id', \Auth::id())->orderBy('updated_at', 'desc')->take(3)->get();

        //获取话费默认(AIS)套餐
        $recharge_packages = $recharge_package->where('is_on', 1)->where('recharge_type_id', 1)->where('operator_id', 1)->get();

        //获取流量默认(AIS)套餐
        $recharge_type_array = \DB::table('recharge_type')->where('operator_id', 1)->pluck('id')->toArray();

        unset($recharge_type_array[0]);

        $recharge_package_webs = $recharge_package->with('recharge_type')->where('is_on', 1)->whereIn('recharge_type_id', $recharge_type_array)->get()->groupBy('recharge_type_id');

        return view(isMobile() . 'mobile_recharge.index', compact('recharge_packages', 'operators', 'recharge_package_webs', 'user_num_histories'));
    }

    public function showPackage(Request $request, RechargePackage $recharge_package) {
        if($request->ajax()) {

            $operator = trim($request->operator);

            $get_operator_id = \DB::table('operator')->where('name', $operator)->first()->id;

            $get_recharge_type_id = \DB::table('recharge_type')->where('name', $operator . '_RECHARGE')->first()->id;

            //获取对应运营商的充值列表(大于100000是因为money最小单位是厘，10厘才是1分钱)
            if($request->recharge_type == 'billpay') {
                $recharge_packages = $recharge_package
                    ->where('is_on', 1)
                    ->where('recharge_type_id', $get_recharge_type_id)
                    ->where('operator_id', $get_operator_id)
                    ->where('money', '>=', '100000')
                    ->orderBy('money','asc')
                    ->get();
            } else {
                $recharge_packages = $recharge_package
                    ->where('is_on', 1)
                    ->where('recharge_type_id', $get_recharge_type_id)
                    ->where('operator_id', $get_operator_id)
                    ->orderBy('money','asc')
                    ->get();
            }

            //获取对应运营商的流量套餐列表
            $recharge_type_array = \DB::table('recharge_type')->where('operator_id', $get_operator_id)->pluck('id')->toArray();

            unset($recharge_type_array[0]);

            $recharge_package_webs = $recharge_package->with('recharge_type')->where('is_on', 1)->whereIn('recharge_type_id', $recharge_type_array)->orderBy('money', 'asc')->get()->groupBy('recharge_type_id');


            $view = view('mobile.layouts._recharge_item',compact('recharge_packages'))->render();

            $view_web = view('mobile.layouts._recharge_web_item',compact('recharge_package_webs'))->render();

            return response()->json(['html'=>$view, 'html_web'=>$view_web]);
        }

    }

    public function checkOperator(Request $request)
    {
        $url = "http://if.topupm.com/api/mobile_operator?";

        $params = array(
              "ref1" => $request->cellphone,
        );

        $paramstring = http_build_query($params);

        $result = Http::get($url.$paramstring);

        return response()->json(['result' => $result->body(), 'status' => $result->successful() ]);
    }

    public function rechargeCallback(Request $request)
    {

        $order = Order::where('recharge_no', $request->transaction_id)->first();

        // $get_recharge_no = $data->transaction_id
        $order->update([
            'recharge_status'    =>  $request->status,
            'recharge_extra'    =>  $request->msg_zh
        ]);

        if($order->recharge_status == 4 && $order->refund_status != 1) {
            //退款
            $apprefund = \EasyWeChat::payment();

            $result = $apprefund->refund->byTransactionId($order->payment_no, 'TK'.$order->payment_no, $order->real_amount, $order->real_amount, [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => $request->msg_zh,
            ]);

            // 更新订单状态
            $order->update([
                'refund_status'    =>  1, //1 已退款
                'refund_no'    =>  'TK'.$order->payment_no
            ]);
        }

        if($order->recharge_status == 2 ) {

            $user_recharge = Order::where('recharge_no', $request->transaction_id)->first();

            $user_num_history = UserNumHistory::where('cellphone_num', $user_recharge->cellphone)->first();

            $operator = RechargePackage::where('id', $user_recharge->recharge_package_id)->first();

            if($user_num_history) {
                $user_num_history->increment('times', 1);
                $user_num_history->update([
                    'is_deleted' => 0,
                ]);
            } else {
                UserNumHistory::create([
                    'user_id' => $user_recharge->user_id,
                    'cellphone_num' => $user_recharge->cellphone,
                    'times' => 1,
                    'is_deleted' => 0,
                    'operator_id' => $operator->operator_id,
                ]);
            }

            //微信公众号推送
            $wx_push = \EasyWeChat::OfficialAccount();

            $wx_push_user = \DB::table('users')->where('id',$user_recharge->user_id)->first();

            if($user_recharge->recharge_extra == 'null') {
                $recharge_extra = '号码：' . show_user_num($user_recharge->cellphone) . '，充值成功。';
            } else {
                $recharge_extra = $user_recharge->recharge_extra;
            }

            if($wx_push_user->wx_open_id) {
                $wx_push_message = $wx_push->template_message->send([
                    'touser' => $wx_push_user->wx_open_id,
                    'template_id' => 'ujCpmx19HVU07mRGECKG756Tzm3DjsEA2bkd9mN2Rkw',
                    'url' => env('APP_URL').'/recharge/record',
                    'data' => [
                        'keyword1' => $user_recharge->cellphone,
                        'keyword2' => $user_recharge->real_amount / 100,
                        'keyword3' => $recharge_extra
                    ],
                ]);
            }

        }

        //扣除积分
        if($order->credit_num > 0) {
            $user =  User::find($order->user_id);

            $credit_less = $order->credit_num;

            $user->update([
                'credit_score' => $user->credit_score - $credit_less,
            ]);


            //积分记录
            UserPromoteRecord::create([
                'user_id' => $user->id,
                'promote_desc' => '积分冲抵话费',
                'promote_type' => 0, //0是减少积分
                'promote_score' => $order->credit_num
            ]);
        }

    }

    public function responseBalance()
    {
        //查询余额
        $balance_push = \EasyWeChat::OfficialAccount();

        $response_balance = Http::asForm()->post('http://if.topupm.com/api/client_api?', [
            'username'          => 'zhaiyanyan',    //账号
            'password'          => 'c159753',   //密码
            'type'              => 'balance_inquiry'
        ]);

        $balance_result = json_decode($response_balance->getBody(), true);

        $balance_push_array = array('o5sess_zO0bqjfvJ8pFBWjLcWqO0','o5sessy2I7UHn8eNmt_8tjVmoXwM','o5sess6FyGyCiZX8_JvY9WaH-MUk');

        //通知管理员剩余余额
        for($i = 0; $i < count($balance_push_array); $i++) {
            $balance_push_message = $balance_push->template_message->send([
                'touser' => $balance_push_array[$i],
                'template_id' => 'BW-sczNrzCsNp1L_fTjJauXKS42LxJHE_6vRbHhJt7I',
                'url' => env('APP_URL').'#',
                'data' => [
                    'keyword1' => '฿'.$balance_result['available_balance'].'铢',
                    'keyword2' => date('Y-m-d H:i:s'),
                ],
            ]);
        }
    }
}
